package gindemo

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/juju/ratelimit"
	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	"net/http"
	"time"
)

func JageMiddle(ctx *gin.Context)  {
	path := ctx.Request.URL.Path

	span := tracer.StartSpan(path,
		ext.SpanKindRPCServer)
	ext.HTTPUrl.Set(span, path)
	ext.HTTPMethod.Set(span, ctx.Request.Method)
	c := opentracing.ContextWithSpan(context.Background(), span)

	ctx.Set("ctx", c)

	ctx.Next()

	ext.HTTPStatusCode.Set(span, uint16(ctx.Writer.Status()))
	span.Finish()
}

func v1middle_1(c *gin.Context)  {
	//第一种传值方式
	c.Set("k1","v1")
	c.Set("k2","v2")
	//第二种传值方式
	c.Keys["k3"]="|xxxx|"

	fmt.Print("======v1middle===")
    c.Next()
}

func v1middle_2(c *gin.Context)  {
	fmt.Print("======v1middle_2===")
	c.Next()
}


//https://www.cnblogs.com/binHome/p/13679737.html
func RateLimitMiddleware(fill int) func(c *gin.Context) {
	bucket := ratelimit.NewBucketWithQuantum(time.Second*time.Duration(fill),25,10)
	return func(c *gin.Context) {

		fmt.Println(bucket.TakeAvailable(1),bucket.Capacity(),bucket.Available())
		// 如果取不到令牌就返回响应
		if bucket.TakeAvailable(1) ==0 {
			c.String(http.StatusOK, "rate limit...")
			fmt.Println("超时了bucket没东西了")
			c.Abort()
			return
		}
		c.Next()
	}
}